package edu.mama.college.controller;

import edu.mama.college.model.JsonResult;
import edu.mama.college.model.User;
import edu.mama.college.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

// @RestController相当于在每个方法上都加上了@ResponseBody注解，即返回json内容到页面
@RestController
public class LoginController {

    @Autowired
    private UserService service;

    /**
     * 注册
     * @param mobile 手机号
     * @param password 密码
     */
    @PostMapping("/register")
    public JsonResult register(@RequestParam("mobile") String mobile,
                               @RequestParam("password") String password) {

//        由于Controller是运行在多线程下，所以会出现线程资源争抢问题，所以在多线程下唯一性不可靠
//        User user = new User(mobile, password);
//        if( service.findByMobile(mobile) != null){
//            return JsonResult.fail("该用户已存在");
//        }
//        service.register(user);
        try{
            User user = new User(mobile, DigestUtils.md5DigestAsHex(password.getBytes()));
            service.register(user);
        }catch(DuplicateKeyException e){
            return JsonResult.fail("该用户已存在");
        }catch(Exception e){
            return JsonResult.fail("程序出错");
        }

        return JsonResult.success();
    }

    /**
     * 登录
     * @param mobile 手机号
     * @param password 密码
     */
    @PostMapping("/login")
    public JsonResult login(@RequestParam("mobile") String mobile,
                            @RequestParam("password") String password,
                            HttpServletRequest request) throws Exception {

        User user = service.findByMobileAndPassword(mobile,  DigestUtils.md5DigestAsHex(password.getBytes()));
        if (user != null) {
            user.setLastLoginTime(new Date());
            service.updateLastLoginTime(user);
            //账号密码匹配，登录成功
            request.getSession().setAttribute("user", user);
            return JsonResult.success();
        } else {
            //账号密码不匹配，登录失败
            return JsonResult.fail("账号或密码错误");
        }
    }

    /**
     * 退出登录
     */
    @GetMapping("/logout")
    public JsonResult logout(HttpServletRequest request) {
        // 作废Session
        request.getSession().invalidate();
        return JsonResult.success();
    }

    @GetMapping("/myself")
    public JsonResult myself(@SessionAttribute(value = "user", required = false) User user) {
        return JsonResult.success(user);
    }
}
